package asia.syimyuzya.android.prime;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends Activity
		implements OnClickListener, OnEditorActionListener {
	
	protected ViewGroup layout;
	protected EditText input;
	protected Button submit;
	protected Button clear;
	protected TextView result;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		layout = (ViewGroup)findViewById(R.id.layout_main);
		input = (EditText)findViewById(R.id.input);
		submit = (Button)findViewById(R.id.submit);
		clear = (Button)findViewById(R.id.clear);
		result = (TextView)findViewById(R.id.result);
		
		input.setOnEditorActionListener(this);
		submit.setOnClickListener(this);
		clear.setOnClickListener(this);
	}
	
	protected void performTest() {
		setAllEnabled(layout, false);
		new PrimeTest() {
			@Override
			protected void onComplete(Integer resultCode) {
				setAllEnabled(layout, true);
				String[] resultString = getResources().
						getStringArray(R.array.result);
				try {
					result.setText(resultString[resultCode]);
				} catch (ArrayIndexOutOfBoundsException e) {
					result.setText(R.string.result_unknown);
				}
			}
		}.execute(input.getText().toString());
	}
	
	/**
	 * 設置控件及其全部子控件是否可用. 採遞歸實現.
	 * 
	 * @param view 欲設置之控件，為ViewGroup時將同時設置全部子控件.
	 * @param enabled 設為true即可用，否則不可用.
	 */
	public static void setAllEnabled(View view, boolean enabled) {
		view.setEnabled(enabled);
		if (view instanceof ViewGroup) {
			ViewGroup group = (ViewGroup)view;
			for (int i = 0; i<group.getChildCount(); i++) {
				setAllEnabled(group.getChildAt(i), enabled);
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v==submit) {
			performTest();
		} else if (v==clear) {
			input.setText("");
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId==EditorInfo.IME_ACTION_SEND) {
			performTest();
			return true;
		}
		return false;
	}
	
}
